<template>
  <div>
    <!-- 搜索栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目编码" prop="bidNumber">
        <el-input
          v-model="queryParams.bidNumber"
          placeholder="请输入项目编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目名称" prop="bidTitle">
        <el-input
          v-model="queryParams.bidTitle"
          placeholder="请输入项目名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="投标结果" prop="isWin">
        <el-select v-model="queryParams.isWin" placeholder="是否中标" clearable>
          <el-option
            v-for="dict in dict.type.is_win"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

<!--      item翻译:条目  element的表单条目-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 按钮区（新增批量删除按钮） -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd()"
          v-hasPermi="['system:dept:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="2">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleBatchDelete"
          v-hasPermi="['manager:bid:remove']"
          :disabled="selectionList.length === 0"
        >批量删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格列表（保留原始表头+添加复选框列） -->
    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="bidList"
      row-key="bidId"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      @selection-change="handleSelectionChange"
    >
    <!-- 批量选择复选框列 -->
    <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>

    <!-- 原始表头（完整保留） -->
    <el-table-column prop="bidTitle" label="投标项目名称" width="140"></el-table-column>
    <el-table-column prop="bidNumber" label="投标项目编号" width="140"></el-table-column>
    <el-table-column prop="bidType" label="采购方式" width="100">
      <template slot-scope="scope">
        <dict-tag :options="dict.type.bid_type" :value="scope.row.bidType"/>
      </template>
    </el-table-column>
    <el-table-column prop="budget" label="预算金额" width="80"></el-table-column>
    <el-table-column label="公告发布时间" align="center" prop="noticeTime" width="160">
      <template slot-scope="scope">
        {{ parseTime(scope.row.noticeTime) }}
      </template>
    </el-table-column>
    <el-table-column prop="signType" label="报名方式" width="100">
      <template slot-scope="scope">
        <dict-tag :options="dict.type.sign_type" :value="scope.row.signType"/>
      </template>
    </el-table-column>
    <el-table-column prop="isWin" label="投标结果" width="100">
      <template slot-scope="scope">
        <dict-tag :options="dict.type.is_win" :value="scope.row.isWin"/>
      </template>
    </el-table-column>

    <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
      <template slot-scope="scope">
        <el-button
          size="mini"
          type="text"
          icon="el-icon-edit"
          @click="handleUpdate(scope.row)"
          v-hasPermi="['manager:bid:edit']"
        >修改</el-button>
        <el-button
          size="mini"
          type="text"
          icon="el-icon-plus"
          @click="handleAdd(scope.row)"
          v-hasPermi="['manager:bid:add']"
        >新增</el-button>
        <el-button
          v-if="scope.row.parentId != 0"
          size="mini"
          type="text"
          icon="el-icon-delete"
          @click="handleDelete(scope.row)"
          v-hasPermi="['manager:bid:remove']"
        >删除</el-button>
      </template>
    </el-table-column>
    </el-table>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="75%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="16">
            <el-form-item label="项目名称" prop="bidTitle">
              <el-input v-model="form.bidTitle" placeholder="请输入项目名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="项目编码" prop="bidNumber">
              <el-input v-model="form.bidNumber" placeholder="请输入项目编码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="预算金额" prop="budget">
              <el-input v-model="form.budget" placeholder="请输入采购预算金额" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="公告发布时间" prop="noticeTime">
              <el-date-picker
                v-model="form.noticeTime"
                type="datetime"
                placeholder="选择公告发布时间"
                value-format="yyyy-MM-dd HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="报名方式" prop="signType">
              <el-select v-model="form.signType" placeholder="请选择报名方式" clearable>
                <el-option
                  v-for="dict in dict.type.sign_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="采购方式" prop="bidType">
              <el-select v-model="form.bidType" placeholder="请选择采购方式" clearable>
                <el-option
                  v-for="dict in dict.type.bid_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="投标结果" prop="isWin">
              <el-radio-group v-model="form.isWin">
                <el-radio
                  v-for="dict in dict.type.is_win"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addBid, delBid, listBid, updateBid } from "@/api/kobe/manager/bids/bid";
import { parseTime } from "../../../../utils/ruoyi";

export default {
  name: "Bid",
  dicts: ['is_win', 'bid_type', 'sign_type'],
  data() {
    return {
      // 表单参数
      form: {
        parentId: 0 // 父项目ID，根项目为0
      },
      // 表单校验规则
      rules: {
        bidTitle: [
          { required: true, message: "项目名称不能为空", trigger: "blur" },
          { min: 1, max: 100, message: "项目名称长度不能超过100个字符", trigger: "blur" }
        ],
        bidNumber: [
          { required: true, message: "项目编码不能为空", trigger: "blur" },
          { min: 1, max: 50, message: "项目编码长度不能超过50个字符", trigger: "blur" }
        ],
        budget: [
          { required: true, message: "预算金额不能为空", trigger: "blur" },
          { pattern: /^([0-9]*[.])?[0-9]+$/, message: "请输入有效的数字", trigger: "blur" }
        ],
        signType: [
          { required: true, message: "请选择报名方式", trigger: "change" }
        ],
        bidType: [
          { required: true, message: "请选择采购方式", trigger: "change" }
        ],
        isWin: [
          { required: true, message: "请选择投标结果", trigger: "change" }
        ],
        noticeTime: [
          { required: true, message: "请选择公告发布时间", trigger: "change" }
        ]
      },
      // 弹出层状态
      open: false,
      title: "",
      // 表格展开状态
      isExpandAll: true,
      // 表格数据
      bidList: [],
      // 加载状态
      loading: true,
      // 表格刷新触发器
      refreshTable: true,
      // 显示搜索栏
      showSearch: true,
      // 分页总数
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bidNumber: undefined,
        bidTitle: undefined,
        isWin: undefined
      },
      // 批量选择的行数据
      selectionList: [] // 新增：存储选中的项
    };
  },
  created() {
    this.getList();
  },
  methods: {
    parseTime,

    // 监听复选框选择变化（新增）
    handleSelectionChange(selection) {
      this.selectionList = selection;
    },

    // 批量删除（新增功能）
    handleBatchDelete() {
      if (this.selectionList.length === 0) {
        this.$modal.msgError("请选择需要删除的数据");
        return;
      }
      // 过滤掉根节点（不允许删除根节点）
      const validIds = this.selectionList
        .filter(item => item.parentId !== 0)
        .map(item => item.bidId);
      if (validIds.length === 0) {
        this.$modal.msgError("根节点不允许删除");
        return;
      }
      this.$modal.confirm(`确定删除选中的${validIds.length}条数据吗？`).then(() => {
        return delBid(validIds);
      }).then(response => {
        if (response.code === 200) {
          this.$modal.msgSuccess("批量删除成功");
          this.getList(); // 刷新列表
          this.selectionList = []; // 清空选择
        } else {
          this.$modal.msgError(response.msg || "批量删除失败");
        }
      }).catch(() => {
        // 取消或失败不处理
      });
    },

    // 新增（支持子项目）
    handleAdd(parentRow) {
      this.reset();
      this.open = true;
      this.title = parentRow ? "新增子项目" : "新增项目";
      this.form.parentId = parentRow ? parentRow.bidId : 0;
    },

    // 修改
    handleUpdate(row) {
      this.reset();
      this.open = true;
      this.title = "修改项目";
      this.form = { ...row }; // 深拷贝避免双向绑定
    },

    // 单个删除
    handleDelete(row) {
      if (row.parentId === 0) {
        this.$modal.msgError("根节点不允许删除");
        return;
      }
      this.$modal.confirm(`确定删除【${row.bidTitle}】吗？`).then(() => {
        return delBid([row.bidId]);
      }).then(response => {
        if (response.code === 200) {
          this.$modal.msgSuccess("删除成功");
          this.getList();
        } else {
          this.$modal.msgError(response.msg || "删除失败");
        }
      }).catch(() => {});
    },

    // 提交表单（新增/修改）
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const api = this.form.bidId ? updateBid : addBid;
          api(this.form).then(response => {
            if (response.code === 200) {
              this.$modal.msgSuccess(this.form.bidId ? "修改成功" : "新增成功");
              this.open = false;
              this.getList();
            } else {
              this.$modal.msgError(response.msg || "操作失败");
            }
          }).catch(() => {
            this.$modal.msgError("接口请求失败");
          });
        }
      });
    },

    // 取消
    cancel() {
      this.open = false;
      this.reset();
    },

    // 重置表单
    reset() {
      this.form = { parentId: 0 };
      if (this.$refs["form"]) {
        this.$refs["form"].resetFields();
      }
    },

    // 重置查询表单
    resetForm(formName) {
      if (this.$refs[formName]) { // 判断表单是否存在
        this.$refs[formName].resetFields();
      }
    },

    // 展开/折叠
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },

    // 搜索
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    // 重置搜索
    resetQuery() {
      this.resetForm("queryForm");//ElementUI内置方法---重置表单的
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        bidNumber: undefined,
        bidTitle: undefined,
        isWin: undefined
      };
      this.handleQuery();
    },

    // 获取列表数据
    getList() {
      this.loading = true;
      listBid(this.queryParams).then(response => {
        console.log( '获得后端数据:'+response)
        this.bidList = response.rows || [];
        this.total = response.total || 0;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
        this.bidList = [];
        this.total = 0;
      });
    }
  }
};
</script>

<style scoped>

</style>
